<?php
namespace app\common\third;

class Excel
{

    /**
     * 使用phpoffice/phpspreadsheet导出excel,支持xlsx格式
     * @param array $data 导出数据
     * @param array $header 表头
     * @param string $fileName 文件名
     * @param string $sheetName sheet名
     * @return string url地址
     */
    static public function exportExcel(array $data, array $header, string $fileName = '', string $sheetName = 'sheet1')
    {
        $fileName = $fileName ?: date('YmdHis', time());
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle($sheetName);
        $sheet->fromArray($header, null, 'A1');
        $sheet->fromArray($data, null, 'A2');
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);

        // 保存到文件 目录地址是 /image/download/
        $env = getenv("SERVER_ENV");
        if ($env == 'test') {
            $filePath = './download/' . $fileName;
        } else {
            $filePath = '/image/download/' . $fileName;
        }
        $writer->save($filePath . '.xlsx');
        
       
        $url = request()->domain() .'/download/'. $fileName . '.xlsx';
        return $url;
    }


    /**
     * 使用phpoffice/phpspreadsheet读取excel
     * @param string $filePath 文件路径
     * @return array
     */
     static public function read(string $filePath)
     {
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filePath);
        $sheet = $spreadsheet->getActiveSheet();
        $rows = $sheet->toArray();
        return $rows;
     }

}